package com.gy.controller.result;


import com.gy.config.BaiduOcrConfig;
import com.gy.controller.assistant.utils.PdfExtractUtil;
import com.gy.controller.common.UserHolder;
import com.gy.entity.Export.CustomCellWriteHandler;
import com.alibaba.excel.EasyExcel;
import com.gy.entity.Export.ExportField;
import com.gy.entity.Export.ExportRequest;
import com.gy.entity.result.Papers;
import com.gy.query.PapersQuery;
import com.gy.result.Result;
import com.gy.service.PapersService;

import com.gy.vo.PageVO;
import com.gy.vo.summary.PapersVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@RestController
@Slf4j
@RequestMapping("/papers")
@Api(tags = "论文接口")
@CrossOrigin
public class PapersController {
    @Autowired
    private PapersService papersService;


    @Autowired
    private PdfExtractUtil pdfExtractUtil;

    @Autowired
    private BaiduOcrConfig baiduOcrUtil;

    @PostMapping("/save")
    @ApiOperation("新增论文")
    public Result AddPapers(@RequestBody Papers papers){
         Result result=papersService.savePapers(papers);
      return result;
    }

    /**
     * 根据openid分页查看某个人的论文信息
     */
    @PostMapping("/getPapers")
    @ApiOperation("根据openid查看某个人的论文信息")
    public Result<PageVO<Papers>> getPapers(@RequestBody PapersQuery papersQuery){
        return papersService.getPapers(papersQuery);
    }

    /**
     * 根据论文id主键查看论文
     */
    @GetMapping("/getPapersById/{id}")
    @ApiOperation("根据论文id主键查看论文")
    public Result getPapersById(@PathVariable Long id){
        Papers serviceById = papersService.getPapersById(id);
        return Result.success(serviceById);
    }


    /**
     * 根据论文id主键删除论文
     */
    @DeleteMapping("/deleteById/{id}")
    @ApiOperation("根据论文id主键删除论文")
    public Result deleteById(@PathVariable Long id){
        return papersService.removePapersById(id);
    }


    /**
     * 更改论文信息
     */
    @PutMapping("/update")
    @ApiOperation("更改论文信息")
    public Result update(@RequestBody Papers papers){
        return papersService.updatePapers(papers);
    }

    /**
     * 通过多个id查询论文信息
     */
    @PostMapping("/getPapersByIds")
    @ApiOperation("通过多个id查询论文信息")
    public Result getPapersByIds(@RequestBody Long[] ids){
        return papersService.getPapersByIds(ids);
    }

    /**
     * excel批量导出
     */
    @PostMapping("/export/papers")
    @ApiOperation("excel批量导出")
    public void exportPapers(@RequestBody ExportRequest request, HttpServletResponse response) throws IOException {
        List<ExportField> fields = request.getFields();
        List<Map<String, Object>> data = request.getData();

        String fileName = "exported_papers.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        // 动态生成表头
        List<List<String>> head = fields.stream()
                .map(field -> Arrays.asList(field.getLabel()))
                .collect(Collectors.toList());

        // 将 Map<String, Object> 转换为 List<List<Object>>
        List<List<Object>> transformedData = data.stream()
                .map(map -> fields.stream()
                        .map(field -> map.get(field.getKey()))
                        .collect(Collectors.toList()))
                .collect(Collectors.toList());

        // 写入数据
        EasyExcel.write(response.getOutputStream())
                .head(head)
                .registerWriteHandler(new CustomCellWriteHandler(fields))
                .sheet("Papers")
                .doWrite(transformedData);
    }

    /**
     * 获取论文汇总
     */
    @GetMapping("/getPapersSummary")
    @ApiOperation("获取论文汇总")
    public Result<List<PapersVO>> getPapersSummary() {
        Long userId = UserHolder.getUser().getUserId();  // Assuming UserHolder is a utility for fetching the logged-in user
        if (userId == null) {
            return Result.error("用户未登录或信息异常");
        }

        // 查询论文数据
        List<Papers> papersList = papersService.lambdaQuery()
                .eq(Papers::getUserId, userId)  // Filter by the logged-in user's ID
                .select(Papers::getTitle, Papers::getPaperType, Papers::getResearchField,
                        Papers::getAuthorRank, Papers::getCorrespondingAuthor, Papers::getJournalName,
                        Papers::getIndexing, Papers::getPublishDate, Papers::getDoi,
                        Papers::getCitationCount, Papers::getKeywords, Papers::getPageRange,
                        Papers::getImpactFactor, Papers::getVolumeNumber, Papers::getIssueNumber,
                        Papers::getIssn, Papers::getCnNumber, Papers::getAbstractContent)
                .list();

        // 将 Papers 转换为 PapersVO
        List<PapersVO> papersVOList = papersList.stream()
                .map(paper -> PapersVO.builder()
                        .title(paper.getTitle())
                        .paperType(paper.getPaperType())
                        .researchField(paper.getResearchField())
                        .authorRank(paper.getAuthorRank())
                        .correspondingAuthor(paper.getCorrespondingAuthor())
                        .journalName(paper.getJournalName())
                        .indexing(paper.getIndexing())
                        .publishDate(paper.getPublishDate())
                        .doi(paper.getDoi())
                        .citationCount(paper.getCitationCount())
                        .keywords(paper.getKeywords())
                        .pageRange(paper.getPageRange())
                        .impactFactor(paper.getImpactFactor())
                        .volumeNumber(paper.getVolumeNumber())
                        .issueNumber(paper.getIssueNumber())
                        .issn(paper.getIssn())
                        .cnNumber(paper.getCnNumber())
                        .abstractContent(paper.getAbstractContent())
                        .build())
                .collect(Collectors.toList());

        return Result.success(papersVOList);
    }

    /**
     * 论文解析接口：从PDF转图片提取OCR→AI解析→返回Papers实体
     * @param request 含filePath（PDF转图片后的imageBasePath）
     * @return 解析后的Papers + 原始OCR文本
     */
    @PostMapping("/parse")
    public Result<Map<String, Object>> parsePapers(@RequestBody Map<String, String> request) {
        try {
            String filePath = request.get("filePath");
            if (filePath == null || filePath.trim().isEmpty()) {
                return Result.error("论文图片路径不能为空");
            }

            // 1提取论文OCR文本（前4页：封面+目录+检索）
            String ocrText = pdfExtractUtil.extractPdfTextFromImages(filePath, baiduOcrUtil);

            Papers papers = pdfExtractUtil.extractPapersByAi(ocrText, true); // 这里新增了第二个参数

            // 返回结果（前端用于填充表单）
            return Result.success(Map.of(
                    "papers", papers,       // 解析后的论文数据
                    "rawOcrText", ocrText   // 原始OCR文本（供调试）
            ));

        } catch (Exception e) {
            log.error("论文解析失败", e);
            return Result.error("解析失败：" + e.getMessage());
        }
    }

}
